<?php
// $Id$

/**
 * Controller_Admin_Users 控制器
 */
class Controller_Admin_Users extends Controller_Abstract
{
	function actiondel()
	{
	$this->union_table = Acctuser::meta();
	#log
	//foreach ($this->_context->ids as $k=>$v)
	//{
		$acct = Acctuser::find('id in (?)',$this->_context->ids)->setColumns('id,acctname')->asArray()->getAll();
		foreach ($acct as $k=>$v)
		{
			Syslog::logs('删除用户:'.$v['acctname']);
		}
		
	//}
	$this->delete(array_merge(array('id'=>$this->_context->ids),$this->_format_appendSql()));
	}
	function _format_appendSql()
	{
		if (isset($_SESSION['acct']))
		{
			if ($_SESSION['acct']['admin_id'] == -1 && $_SESSION['acct']['agent_id'] == -1)
			{
			//为管理
				//$append['']
				$append['admin_id'] = $_SESSION['acct']['id'];
				
			}else
			{
				$append['admin_id'] = $_SESSION['acct']['admin_id'];
				$append['agent_id'] = Acct::_get_have_acctid($_SESSION['acct']['id'], $_SESSION['acct']['admin_id']);
				$append['agent_id'][] = $_SESSION['acct']['id'];
				
			}
		}
		return $append;
	}
	/**
	 * 认证号码
	 */
	function actioninsertauth()
	{
		if($this->_context->isPOST())
		{
			$acctname = ($_SESSION['acct']['acctname']);
		$num = Acctuser::insertAuth($acctname);
		$str = $num<=2 ? '发起成功,请等待回铃':'每日只能使用3次';
		return $this->success($str);
		}
		
	}
	function actionbatvips()
	{
	    $idss = ($this->_context->ids);
	    $flag = intval($this->_context->flag);
	    //$idss = explode(',', $ids);
	    if(count($idss))
	    {
	    	$param = array('id'=>$idss);
	        $acctname = Acctuser::find($param)->setColumns('id,acctname')->asArray()->getAll();
	        $users = Helper_Array::toHashmap($acctname, 'id','acctname');
	        
	        foreach ($idss as $k=>$v)
	        {
	            QDB::getConn()->execute("call fscall.acct_vippay('{$users[$v]}',{$flag})");
				QDB::getConn()->close();
	        }
	        
	        return $this->success('操作成功');
	    }else{
	    return $this->error('请选择用户');
	    }
	}
	/**
	 * 开通关闭VIP
	 */
	function actionvips()
	{
		#0 =kai 1=guan
		$flag = intval($this->_context->flag);
		$acctid = intval($this->_context->acctid);
		if($_SESSION['acct']['acclevel'] == 3)
		{
			$acctuser = Acctuser::find('id = ?',$_SESSION['acct']['id'])->getOne();
		}else{
			$acctuser = Acctuser::find(array_merge($this->_format_appendSql(),array('id'=>$acctid)))->getOne();
			
		}
		
		if (!$acctuser->id())
		{
			return $this->error('用户不存在');
		}else
		{
			if ($flag == 0)
			{
				QDB::getConn()->execute("call fscall.acct_vippay('{$acctuser->acctname}',0)");
				QDB::getConn()->close();
				return $this->success('开通成功');
			}else{
				QDB::getConn()->execute("call fscall.acct_vippay('{$acctuser->acctname}',1)");
				QDB::getConn()->close();
				return $this->success('关闭成功');
			}
		}
		
	}
	function actionindex()
	{
		$this->union_table = Acctuser::meta();
		$agent_list = Acct::_get_arrayinfo($this->_format_appendSql());
		$this->_view['agent_list'] = $agent_list;
		$limit  = $this->_format_appendSql();
		if (isset($_POST['agent_id']) && isset($limit['agent_id']) &&  in_array($_POST['agent_id'], $limit['agent_id']))
		{
			$limit['agent_id'] = intval($_POST['agent_id']);
		}
		$this->lists($limit);
	}
	
	function actionmake()
	{
		$this->union_table = Acctuser::meta();
		$handle = new helper_autoinsert($this->union_table);
		$form = new form_users_make(url($this->_context->controller_name.'/'.$this->_context->action_name));
		//$result = $handle->add($form, 'id',$_GET);
		
		if ($this->_context->isGET())
		{
			//列出下级代理
				//$query = $this->_format_appendSql()
				$sub_agentArray = Acct::find($this->_format_appendSql())->setColumns('id,acctname')->asArray()->getAll();
				$sub_agentArray = Helper_Array::toHashmap($sub_agentArray, 'id','acctname');
				$form->element('agent_id')->items = $sub_agentArray;
				$form->element('admin_id')->value = Acct::cur_admin_id();
				$form->element('rategroupid')->items =  Rategroup::_get_arrayinfo(array('agent_id'=>$_SESSION['acct']['id']));
		 		$form->element('rategroupid_acall')->items = Rategroup::_get_arrayinfo(array('agent_id'=>$_SESSION['acct']['id']));
		 		
			$this->_view['form'] = $form;
			$this->_viewname = '../form/add';
			
		}else {
			$valus = $_POST;
			$start_acct = intval($valus['begin_acctname']);
			unset($valus['begin_acctname']);
			$start_num = intval($valus['acctname_num']);
			unset($valus['acctname_num']);
			$ok = 0;
			for ($i=1;$i<=$start_num;$i++)
			{
				$acctname = $start_acct + $i;
				$valus['acctname'] = $acctname;
				$isOne = Acctuser::find('acctname = ?',$acctname)->getCount('id');
				if($isOne )
				{}else{
				//不存在
					$acctuser = new Acctuser($valus);
					try {
						$acctuser->save(0,'create');
						$ok+=1;
					} catch (Exception $e) {
						//dump($valus);die;
					}
				}
				
			}
			Syslog::logs('成功生成'.$ok.' 条用户记录');
			return $this->success('成功生成'.$ok.' 条用户记录');
			
			//return call_user_func_array(array($this,$handle->status),$result);
		}
	}
	
	function actionadd()
	{
		$this->union_table = Acctuser::meta();
		$handle = new helper_autoinsert($this->union_table);
		$form = new form_users_add(url($this->_context->controller_name.'/'.$this->_context->action_name));
		if($_SESSION['acct']['balance_update'] == 0 && $_SESSION['acct']['acclevel'] != 0)
		{
			$form->remove('balance');
		}
		$result = $handle->add($form, 'id',$_GET);
		
		if ($this->_context->isGET())
		{
			
			//列出下级代理
				if($this->_context->id)
				{
					$acctuser = Acctuser::find('id = ?',intval($this->_context->id))->setColumns('id,agent_id')->getOne();
					$agent_id = $acctuser->agent_id;
					$group = Rategroup::_get_agentRateinfo($agent_id);
					$group_a = Rategroup::_get_agentRateinfo($agent_id);
				}else{
					exit('不允许直接添加用户');
				}
				//$sub_agentArray = Acct::find($this->_format_appendSql())->setColumns('id,acctname')->asArray()->getAll();
			//	$sub_agentArray = Helper_Array::toHashmap($sub_agentArray, 'id','acctname');
				$result->element('agent_id')->items = Acct::_getsubAcctHashMap();
				$result->element('admin_id')->value = Acct::cur_admin_id();
				$result->element('rategroupid')->items =  $group;
		 		$result->element('rategroupid_acall')->items = $group_a;
		 		
			$this->_view['form'] = $result;
			$this->_viewname = '../form/add';
			
		}else {
			
			Syslog::logs('编辑用户:'.$this->_context->acctname);
			$id = intval($this->_context->id);
			//if($id)@QDB::getConn()->execute("update acct_user set expireddate = from_unixtime(unix_timestamp(activedate)+ expireddays*86400,'%Y-%m-%d') where id = '{$id}'");
			@QDB::getConn()->execute("update sip_bindexten_buddies set secret ='{$this->_context->password}' where accountcode = '{$this->_context->acctname}'");
			return call_user_func_array(array($this,$handle->status),array($result));
		}
	}
	function actionimport()
	{
		$query = $this->_format_appendSql();
		if ($this->_context->isGET())
		{
			$form = new Form_users_import(url($this->_context->controller_name.'/'.$this->_context->action_name));
			
			
			if (!isset($query['agent_id']))
			{
				$items = Acct::_get_arrayinfo($query);
			}else
			{
				$items = array($_SESSION['acct']['id']=>$_SESSION['acct']['acctname']);
			}
				$form->element('rategroupid')->items =  Rategroup::_get_arrayinfo(array('agent_id'=>$_SESSION['acct']['id']));
		 		$form->element('rategroupid_acall')->items = Rategroup::_get_arrayinfo(array('agent_id'=>$_SESSION['acct']['id']));
		 		
			$form->element('agent_id')->items = $items;
			$this->_view['form'] = $form;
			$this->_viewname = '../users/add';

		}else if ($this->_context->isPOST())
		{
			//add users
			$userfile = isset($this->_context->userfile)?trim($this->_context->userfile):'';
			if (is_file($userfile))
			{
				$fileinfo = pathinfo($userfile);
				if($fileinfo['extension'] != 'txt')
				{
					return $this->error('导入文件必须是TXT文件');
				}
				$agent_id = !isset($query['agent_id'])?intval($this->_context->agent_id):$_SESSION['acct']['id'];
				$admin_id = Acct::cur_admin_id();
				$bindexten_type = intval($this->_context->bindexten_type);
				$bindexten_cb = $this->_context->bindexten_cb;
				$bindexten_sip = $this->_context->bindexten_sip;
				$bindexten = $this->_context->bindexten;
				$rategroupid = $this->_context->rategroupid;
				$rategroupid_acall = $this->_context->rategroupid_acall;
				$handle = fopen($userfile, 'r');
				if($handle)
				{
					$split_char = ',';
					$i = 0;
					$ok = 0;
					$no = 0;
					$line_num = 0;
					$err_line = '';
					while (!feof($handle))
					{
						$line_num +=1;
						$lineCard = fgets($handle,400);
						$Split_arr = explode($split_char, $lineCard);
						if(QValidator::validate_between(count($Split_arr), 4, 5))
						{
							if(strlen($Split_arr[0])>0 && strlen($Split_arr[1])>0 && strlen($Split_arr[2])>0 && strlen($Split_arr[3])>0 )
							{
								$day = intval($Split_arr[3]);
								$userArr = array(
									'acctname'=>trim($Split_arr[0]),
									'password'=>$Split_arr[1],
									'balance'=>$Split_arr[2],
									'expireddays'=>floor((strtotime($Split_arr[3])-time())/86400),
									'expireddate'=>$Split_arr[3],
									'bindtel'=>isset($Split_arr[4])?$Split_arr[4]:'',
									'agent_id'=>$agent_id,
									'admin_id'=>$admin_id,
									'bindexten_type'=>$bindexten_type,
									'bindexten_cb'=>$bindexten_cb,
									'bindexten_sip'=>$bindexten_sip,
									'bindexten'=>$bindexten,
									'rategroupid'=>$rategroupid,
									'rategroupid_acall'=>$rategroupid_acall
								);
								$user = Acctuser::find('acctname = ?',$userArr['acctname'])->getOne();
								if($user->id())
								{
									Acctuser::meta()->deleteWhere('id = '.$user->id);	
									//$err_line .= ','.$line_num;
								}
								if (Helper_Param::_call($userArr['acctname']))
								{
									try {
										$user = new Acctuser($userArr);
										$user->save(0,'create');
// 											if(isset($Split_arr[4])){//设置了绑定号码
// 											$bind = new Userbindtel();
// 											$bind->agent_id = $agent_id;
// 											$bind->admin_id = $admin_id;
// 											$bind->acctname = $Split_arr[0];
// 											$bind->bindtel = isset($Split_arr[4])?$Split_arr[4]:'';
// 											$bind->save(0,'create');
// 											}
										
										$ok +=1;
									} catch (Exception $e) {
										$err_line .= ','.$line_num;
									}
								}
							}else
							{
								$no +=1;
								$err_line .= ','.$line_num;
								continue;
							}
						}else
						{
							$no +=1;
							$err_line .= ','.$line_num;
							continue;
						}
					}
					fclose($handle);
					//删除文件
					@unlink($cardfile);
					Syslog::logs('导入用户:'.$ok.'条用户数据');
					return $this->success(sprintf('成功导入%d条记录，失败%d条，分别存在:%s',$ok,$no,$err_line));
				}else
				{
					return $this->error('文件打开失败');
				}
			}else
			{
				return $this->error('文件不存在,请重新上传');
			}
					
		}
	}
	function actionoutput()
	{
		if($_SESSION['acct']['downloaduser_level'] ==0 && $_SESSION['acct']['acclevel'] != 0)
		{
			$output = new Helper_dboutput(array(array('您没有权限导出数据')));
			$output->output_txt();
			die;
		}
		$param = $_SESSION['lastsql'];
		$this->union_table = Acctuser::meta();
		$data = call_user_func_array(array($this->union_table,'find'), $param);
		$data = $data->setColumns('acctname,password,balance,expireddays')->asArray()->getAll();
		
		$output = new Helper_dboutput($data);
		$output->output_txt();
	}
	function actionchange()
	{
		
		if($_SESSION['acct']['update_level'] == 0 && $_SESSION['acct']['acclevel'] != 0)
		{
			return $this->error('对不起,您没有权限批量修改');
		}
		if ($this->_context->isGET())
		{
				$this->_view['rategroupid'] =  Rategroup::_get_arrayinfo(array('agent_id'=>$_SESSION['acct']['id']));
		 		$this->_view['rategroupid_acall']  = Rategroup::_get_arrayinfo(array('agent_id'=>$_SESSION['acct']['id']));
		}else {
			$param = $_SESSION['lastsql'];
			$obj = call_user_func_array(array(Acctuser::meta(),'find'), $param);
			$acctUser = $obj->setColumns('id')->asArray()->getAll();
			//$sql = helper_disposeparam::parse($param);
			//$acct = Acctuser::find($param)->getAll();
			
			if (count($acctUser)>0)
			{
				$acctUser = Helper_Array::toHashmap($acctUser, 'id','id');
				$ids = Helper_Array::toHashmap($acctUser, 'id','id');
				$post = $_POST;
				$upsql = " UPDATE acct_user set %s where id in (%s)";
				$setsql = array();
// 				if (isset($post['balance']))
// 				{
// 					$setsql[] = " balance =  ".intval($post['balance']);
// 				}else if (isset($post['append_balance']) && $post['append_balance'])
// 				{
// 					$setsql[] = " balance = balance + ".intval($post['append_balance']);
// 				}
				if(isset($post['balanceflag']) && $post['balanceflag'] == 1 && isset($post['append_balance']) )
				{
					$setsql[] = " balance = balance + ".intval($post['append_balance']);
				}
				if (isset($post['expireddate']) && $post['expireddate'])
				{
					$setsql[] = " expireddate = '{$post['expireddate']}'";
				}
// 				if (isset($post['minute_len']) && $post['minute_len'])
// 				{
// 					$setsql[] = " minute_len = ".intval($post['minute_len']);
// 				}
				if (isset($post['talk_timelong']) && $post['talk_timelong'])
				{
					$setsql[] = " talk_timelong = ".intval($post['talk_timelong']);
				}
				if (isset($post['bindexten_type']) && $post['bindexten_type'] != -1)
				{
					$setsql[] = " bindexten_type = ".intval($post['bindexten_type']);
				}
				if (isset($post['bindexten']) && $post['bindexten'])
				{
					$setsql[] = " bindexten = '".intval($post['bindexten'])."'";
				}
				if (isset($post['bindexten_sip']) && $post['bindexten_sip'])
				{
					$setsql[] = " bindexten_sip = '".intval($post['bindexten_sip'])."'";
				}
				if (isset($post['bindexten_cb']) && $post['bindexten_cb'])
				{
					$setsql[] = " bindexten_cb = '".intval($post['bindexten_cb'])."'";
				}
				if (isset($post['bindexten_cb']) && $post['bindexten_cb'])
				{
					$setsql[] = " bindexten_cb = '".intval($post['bindexten_cb'])."'";
				}
				if (isset($post['enable']) && $post['enable'] != -1)
				{
					$setsql[] = " enable = ".intval($post['enable']);
				}
				if (isset($post['limitbalance']) && $post['limitbalance'])
				{
					$setsql[] = " limitbalance = ".intval($post['limitbalance']);
				}
				if (isset($post['callerid']) && $post['callerid'])
				{
					$setsql[] = " callerid = ".intval($post['callerid']);
				}
				if (isset($post['rategroupid']) && $post['rategroupid'] != -1)
				{
					$setsql[] = " rategroupid = ".intval($post['rategroupid']);
				}
				if (isset($post['rategroupid_acall']) && $post['rategroupid_acall'] != -1)
				{
					$setsql[] = " rategroupid_acall = ".intval($post['rategroupid_acall']);
				}
				if (count($setsql)>0)
				{
					$upsql = sprintf($upsql,implode(',',$setsql),implode(',',$acctUser));
					try {	
					QDB::getConn()->execute($upsql);
					Syslog::logs('批量修改:'.count($acctUser).'条用户数据');
					return $this->success('修改成功');
					} catch (Exception $e) {
						return $this->error('修改失败');
					}
					
				}else{
					return $this->error('没有被修改的项目');
				}
				
			}else {
				return $this->error('没有匹配的数据');
			}
		}
	}
	function actionvip()
	{
		if($this->_context->isGET())
		{
			$acct = Acctuser::checkAcctname($_SESSION['acct']['acctname']);
			$this->_view['acctuser'] = $acct;
		}
	}
	function actioncallpwd()
	{
	#0 =不要密码 1=要密码
		$flag = intval($this->_context->flag);
		$acctid = intval($this->_context->acctid);
		if($_SESSION['acct']['acclevel'] == 3)
		{
			$_SESSION['acct']['callpwd'] = $flag;
			$acctuser = Acctuser::find('id = ?',$_SESSION['acct']['id'])->getOne();
		}else{
			$acctuser = Acctuser::find(array_merge($this->_format_appendSql(),array('id'=>$acctid)))->getOne();
			
		}
		
		if (!$acctuser->id())
		{
			return $this->error('用户不存在');
		}else
		{
			if ($flag == 0)
			{
				$acctuser->callpwd = 0;
				$acctuser->save(0,'update');
				
				return $this->success('设置为普通呼叫成功');
			}else{
				$acctuser->callpwd = 1;
				$acctuser->save(0,'update');
				return $this->success('设置为加密呼叫成功');
			}
		}
	}
    function actionauthenbilltime()
    {
        $uid = intval($this->_context->uid);
        $acct = Acctuser::find('id = ?',$uid)->setColumns('id,acctname,balance')->getOne();
        
        if (!$acct->id())
        {
            return $this->error('不存在用户');
        }else if($acct->balance < 0)
        {
            return $this->error('余额不足');
        }else{
            $black = Submitfilter::find('acctname = ?',$acct->acctname)->getOne();
            if($black->id())
            {
                return $this->error('黑名单用户');
            }else{
                $result = QDB::getConn('fscall')->execute("select fscall.authen_billtime('{$acct->acctname}','$acct->acctname',1)")->fetchOne();
                QDB::getConn('fscall')->close();
                return $this->success('最大通话时间'.$result.'秒');
            }
        }
    }
}


